/**
 * 分页查询方法
 * @param url
 * @param pageNo
 * @param pageSize
 */
function submit(url, pageNo, pageSize) {
    if(pageNo === undefined){
        pageNo = initPageNo;
    }
    if(pageSize === undefined){
        pageSize = initPageSize;
    }

    layui.use(['table', 'laypage','form'], function () {
        let table = layui.table;
        let laypage = layui.laypage;

        let templateNo = $('#templateNo').val();
        let templateName = $('#templateName').val();
        let templateStatus = $('#templateStatus').val();
        let sealType = $('#sealType').val();
        let auditStatus = $('#auditStatus').val();
        let createTime = $('#createTime').val();
        let updateTime = $('#updateTime').val();

        //TODO 获取当前租户Id  channelId

        let channelId = $('#channelId').val();

        //第一个实例
        table.render({
            elem: '#searchTable'
            ,url: url //数据接口
            ,page: false //开启分页
            ,toolbar: '#tableToolbar'
            , method: 'POST'
            , headers: {"token": getCookie("token")}
            , contentType : "application/json"
            , where: {templateNo:templateNo,templateName:templateName,channelId:channelId,templateStatus:templateStatus,sealType:sealType,createTime:createTime,updateTime:updateTime,auditStatus:auditStatus,pageNo:pageNo,pageSize:pageSize}
            ,cols: [[ //表头
                {field: 'dataId',type: 'checkbox'}
                , {field: 'templateNo', title: '模板编码', width: '150', align: 'center'}
                , {field: 'templateName', title: '模板名称', width: '200',align: 'center'}
                , {field: 'sealTypeName', title: '签章类型', width: '100',align: 'center'}
                , {field: 'templateStatusName', title: '状态', width: '100',align: 'center'}
                , {field: 'auditStatusName', title: '审核状态', width: '100',align: 'center'}
                , {field: 'createName', title: '创建人', width: '150',align: 'center'}
                , {field: 'createTime', title: '创建时间',width: '150',align: 'center',templet: function (d) {return toDateString(d.createTime);}}
                , {field: 'operatorName', title: '最后一次修改人', width: '150',align: 'center'}
                , {field: 'updateTime', title: '修改时间', width: '150',align: 'center',templet: function (d) {return toDateString(d.updateTime);}}
                , {field: 'version', title: '版本', width: '100',align: 'center'}
                , {field: 'remark', title: '备注', width: '180',align: 'center'}
                , {field: 'right', width: '250', title: '操作', align: 'center', toolbar: '#barSearch'} //添加工具条,
            ]]
            ,parseData: function(res){ //将原始数据解析成 table 组件所规定的数据
                return {
                    "code": res.code, //解析接口状态
                    "msg": res.msg, //解析提示文本
                    "count": res.data.pageInfo.totalCount, //解析数据长度
                    "pageNo": res.data.pageInfo.pageNo, //解析数据长度
                    "pageSize": res.data.pageInfo.pageSize, //解析数据长度
                    "data": res.data.pageInfo.list //解析数据列表
                };
            }
            ,done:function (res) {
                //增加自定义样式
                beautyCell();
                //自定义分页
                laypage.render({
                    elem: 'tablePage'
                    , curr: res.pageNo
                    , count: res.count
                    , limit: res.pageSize
                    ,layout: ['page', 'limit','count', 'skip']
                    ,limits:['20','30','50','100']
                    ,theme: '#1b2b34'
                    ,jump: function(obj,first){
                        if(!first){
                            submit(url, obj.curr, obj.limit);
                        }
                    }
                });
            }
        });

        //工具条
        table.on('tool(searchTable)', function(obj){
            let data = obj.data;
            if(obj.event === 'preview'){
                let id = data.id;
                xadmin.open("预览合同","./look.html?id="+id,750,700);
            }
            if(obj.event === 'update'){
                let id = data.id;
                xadmin.open("修改模板","./edit.html?id="+id,550,710);
            }
            if(obj.event === 'updateStatus'){
                let templateStatus = data.templateStatus;
                let id = data.id;
                let msg;
                let confirmStatus;
                if(templateStatus === 1){
                    msg = "确定要停用吗？";
                    confirmStatus = 0;
                }else {
                    msg = "确定要启用吗？";
                    confirmStatus = 1;
                }
                layer.confirm(msg, {icon: 3, title:'修改状态'}, function(index){
                    updateStatus(confirmStatus,id,index);
                });
            }
            if(obj.event === 'download'){
                let refId = data.refId;
                if(refId !== null && refId !== ""){
                    exportTemplate(refId);
                }else {
                    errorMsg("模板文件不存在！");
                }
            }
        });

        //头部按钮
        table.on('toolbar(searchTable)', function(obj){
            let checkStatus = table.checkStatus(obj.config.id);
            switch(obj.event){
                case 'create':
                    xadmin.open("新增模板","./add.html",700,650);
                    break;
                case 'createAudit':
                    let templateArray = checkStatus.data;
                    if(templateArray.length === 0) {
                        errorMsg("请选择要配置审批流的模板！");
                        return false;
                    }
                    if(templateArray.length > 1) {
                        errorMsg("请选择一个模板进行配置！");
                        return false;
                    }
                    let id = templateArray[0].id;
                    xadmin.open("配置审批流","./audit.html?id="+id,600,550);
                    break;
                case 'export':
                    let data = checkStatus.data;
                    if(data.length === 0) {
                        alert("请选择导出模板");
                        return false;
                    }
                    let ids = [];
                    $.each(data, function(i, item){
                        ids.push(item.refId);
                    });
                    exportTemplate(ids);
                    break;
            }
        })

    });
}

/**
 * 修改模板状态
 * @param confirmStatus
 */
function updateStatus(confirmStatus,id,index) {
    let url = serverPre + "/manager/scs/v2/template/updateSts";
    let data = JSON.stringify({'templateStatus':confirmStatus,'id':id});
    $.ajax({
        url: url,
        data: data,
        type: 'POST',
        contentType: 'application/json',
        headers: {'token': getCookie('token')},
        success: function (res) {
            if (res.code === 0) {
                layer.close(index);
                parent.location.reload();
            }
        },
        error: function (err) {
            errorMsg(err);
        }
    });
}

/**
 * 隐藏文本编辑器
 */
function hideLayEdit(form) {
    $("#templateEdit").parent().parent().hide();
    form.render();
}

/**
 * radio事件监听
 */
function radioListener(form) {
    form.on('radio(templateListen)', function(data){
        if(data.value === "1"){
            $("#templateEdit").parent().parent().hide();
            $("#templateExtId").parent().parent().show();
            form.render();
        }
        if(data.value === "2"){
            $("#templateExtId").parent().parent().hide();
            $("#templateEdit").parent().parent().show();
            form.render();
        }
    });
}

/**
 * 新增页面select事件监听
 */
function selectListener(form) {
    //默认隐藏公章规则号
    $("#officialSealId").parent().hide();
    form.on('select(sealType)', function(data){
        if(data.value === "1"){ //私章
            $("#officialSealId").parent().hide();
            form.render();
        }else {
            //TODO 获取产品编号
            var proCode = $('#channelId').val();
            debugger;
            queryOfficalSeal(form,null,proCode);
            $("#officialSealId").parent().show();
            form.render();
        }
    })
    form.on('select(channelId)', function(data){
            var proCode = $('#channelId').val();
            queryOfficalSeal(form,null,proCode);
            //获取模板编号前缀
            queryTemplateNoPrefix(form,proCode);
            form.render();
    })
}

/**
 * 获取模板编号前缀
 * @param form
 */
function queryTemplateNoPrefix(form,proCode) {
    let url = serverPre + "/manager/scs/v2/template/queryTemplatePrefix?productCode="+proCode;
    $.ajax({
        url: url,
        type: 'GET',
        contentType: 'application/json',
        headers: {'token': getCookie('token')},
        success: function (res) {
            if (res.code === 0) {
                console.log(res.data.templateNoPrefix);
                $('#templateNoPrefix').html(res.data.templateNoPrefix);
            }
        },
        error: function (err) {
            errorMsg(err);
        }
    });
}

/**
 * 编辑页面select事件监听
 * @param form
 */
function selectListener2(form) {
    form.on('select(sealType)', function(data){
        var templateNo = $(this).parent().parent().parent().parent().parent()[0][0].value;
        if(data.value === "1"){ //私章
            $("#officialSealId").parent().hide();
            form.render();
        }else {
            let url = serverPre + "/manager/scs/v2/template/officialSealId/"+templateNo;
            $.ajax({
                url: url,
                type: 'GET',
                dataType: 'json',
                async:false,
                headers: {'token': getCookie('token')},
                success: function (res) {
                    if (res.code === 0) {
                        let result =  res.data.list;
                        var ids = [];
                        $.each(result,function (i,item) {
                            ids.push(item.code);
                        });
                        queryOfficalSeal(form,ids);
                        $("#officialSealId").parent().show();
                        form.render();
                    }
                },
                error: function (err) {
                    errorMsg(err);
                }
            });
        }
    })
}

/**
 * 查询公章规则号--所有
 * @param form
 */
function queryOfficalSeal(form,ids,channelNo) {
    let url = serverPre + "/manager/scs/v2/template/officialSealId/list/pro?productCode="+channelNo;
    let data = JSON.stringify({'pageNo':'1','pageSize':'999'});
    $("#officialSealId").empty();
    $.ajax({
        url: url,
        data: data,
        type: 'POST',
        contentType: 'application/json',
        headers: {'token': getCookie('token')},
        success: function (res) {
            if (res.code === 0) {
                let result = res.data.list;
                $.each(result,function (i,item) {
                    let code = item.code;
                    let name = item.name;
                    let content = "<input type='checkbox' name='officalSealBox' id='"+code+"' value='"+code+"' lay-skin='primary' title='"+name+"'>";
                    $("#officialSealId").append(content);
                });
                if(ids !== undefined && ids !== null){
                    $.each(ids,function (i,item) {
                        $("#"+item).prop("checked",true);
                    })
                }
                form.render();
            }else if(res.code == 100){
                errorMsg(res.msg)
            }
        },
        error: function (err) {
            errorMsg(err);
        }
    });
}


/**
 * 查询渠道
 */
function queryChannels(form) {
    let url = serverPre + "/manager/scs/v2/product";
    let content = '<option value="">模板渠道</option>'; //全局变量
    //let data = JSON.stringify({'pageNo':'1','pageSize':'999'});
    $.ajax({
        url: url,
        type: 'GET',
        contentType: 'application/json',
        headers: {'token': getCookie('token')},
        success: function (res) {
            if (res.code === 0) {
                let result = res.data.pageInfo.list;
                $.each(result,function (i,item) {
                    let channelNo = item.code;
                    let channelName = item.productName;
                    content += '<option value = "' + channelNo + '">' + channelName + '</option>'
                });
                $("#channelId").html(content);
                form.render('select');
            }else if(res.code == 100){
                errorMsg(res.msg)
            }
        },
        error: function (err) {
            errorMsg(err);
        }
    });
}

/**
 * 查询公章规则号--单条
 * @param form
 */
function queryOfficalId(id,form) {
    let url = serverPre + "/manager/scs/v2/template/officialSealId/"+id;
    $.ajax({
        url: url,
        type: 'GET',
        contentType: 'application/json',
        headers: {'token': getCookie('token')},
        success: function (res) {
            if (res.code === 0) {
                let result = res.data.list;
                $.each(result,function (i,item) {
                    let code = item.code;
                    let name = item.name;
                    let content = "<input type='checkbox' name='officalSealBox' value='"+code+"' lay-skin='primary' disabled='disabled' checked title='"+name+"'>";
                    $("#officialSealId").append(content);
                });
                form.render();
            }else if(res.code == 100){
                errorMsg(res.msg)
            }
        },
        error: function (err) {
            errorMsg(err);
        }
    });
}

/**
 * 初始化签章类型--所有
 */
function querySealType(form) {
    let url = serverPre + "/manager/scs/v2/template/sealType/list";
    let content = '<option value="">签章类型</option>'; //全局变量
    let data = JSON.stringify({'pageNo':'1','pageSize':'999'});
    $.ajax({
        url: url,
        data: data,
        type: 'POST',
        contentType: 'application/json',
        headers: {'token': getCookie('token')},
        success: function (res) {
            if (res.code === 0) {
                let result = res.data.list;
                $.each(result,function (i,item) {
                    let sealType = item.code;
                    let sealTypeName = item.name;
                    content += '<option value = "' + sealType + '">' + sealTypeName + '</option>'
                });
                $("#sealType").html(content);
                form.render('select');
            }else if(res.code == 100){
                errorMsg(res.msg)
            }
        },
        error: function (err) {
            errorMsg(err);
        }
    });
}

/**
 * 查询审核状态
 */
function queryAuditStatus(form) {
    let url = serverPre + "/manager/scs/v2/template/auditStatus/list";
    let content = '<option value="">审核状态</option>'; //全局变量
    let data = JSON.stringify({'pageNo':'1','pageSize':'999'});
    $.ajax({
        url: url,
        data: data,
        type: 'POST',
        contentType: 'application/json',
        headers: {'token': getCookie('token')},
        success: function (res) {
            if (res.code === 0) {
                let result = res.data.list;
                $.each(result,function (i,item) {
                    let auditStatus = item.code;
                    let auditStatusName = item.name;
                    content += '<option value = "' + auditStatus + '">' + auditStatusName + '</option>'
                });
                $("#auditStatus").html(content);
                form.render('select');
            }else if(res.code == 100){
                errorMsg(res.msg)
            }
        },
        error: function (err) {
            errorMsg(err);
        }
    });
}

/**
 * 新增模板
 * @param url
 * @param data
 * @returns {boolean}
 */
function saveTemplate(url,data) {
    $.ajax({
        url: url,
        data: data,
        type: 'POST',
        contentType: 'application/json',
        headers: {'token': getCookie('token')},
        success: function (res) {
            if (res.code === 0) {
                layui.use('layer',function(){
                    let layer = layui.layer;
                    layer.msg("保存成功!",{
                        icon:1,
                        time:2000,
                        end: function () {
                            var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
                            parent.layer.close(index);
                            parent.location.reload();
                        }
                    });
                });
            }else{
                let layer = layui.layer;
                var errorMsg1 = "保存失败!";
                if (isNotBlank(res.msg)){
                    errorMsg1 = res.msg
                }
                layer.msg(errorMsg1,{
                    icon:1,
                    time:2000,
                    end: function () {
                        var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
                        // parent.layer.close(index);
                        // parent.location.reload();
                    }
                });
            }
        },
        error: function (err) {
            errorMsg("保存失败")
        }
    });
    return false;
}


/**
 * 删除模板
 */
function confirmMsg(url) {
    layui.use('layer',function(){
        var layer = layui.layer;
        layer.confirm('确定要删除吗？', {
            btn: ['确定', '取消']
        }, function(index){//按钮一的回调
            $.ajax({
                url: url,
                type: 'GET',
                dataType: 'json',
                async:false,
                headers: {'token': getCookie('token')},
                success: function (res) {
                    if (res.code === 0) {
                        layui.use('layer',function(){
                            let layer = layui.layer;
                            layer.msg("删除成功!",{
                                icon:1,
                                time:2000,
                                end: function () {
                                    layer.close(layer.index);
                                    $('#reloadTemplateData').trigger("click");
                                }
                            });
                        });
                    }else {
                        errorMsg("删除失败")
                    }
                },
                error: function (err) {
                    alert(err);
                }
            });
            return false;
        }, function(index){//按钮二的回调

        });
    })
}

/**
 * 美化按钮样式
 */
function beautyCell() {
    $("[data-field='templateStatusName']").children().each(function (index,item) {
        if(item.textContent === '启用'){
            $(this).css("color","#228b22");
        }
        if(item.textContent === '禁用'){
            $(this).css("color","#ff0000");
        }
    })
}

/**
 * 查看窗口
 * @param result
 */
function buildOpenWin(result,form){
    if(result === undefined || result === null){
        errorMsg("返回数据为空");
    }
    if(result.templateNo !== ""){
        $('#templateNo').val(result.templateNo);
    }
    if(result.templateName !== ""){
        $('#templateName').val(result.templateName);
    }
    if(result.resourceName !== ""){
        $('#templateResource').val(result.resourceName);
    }
    if(result.sealType === 1){
        $("#officialSealId").parent().hide();
    }else {
        queryOfficalId(result.templateNo,form);
    }
    if(result.sealTypeName !== ""){
        $('#sealType').val(result.sealTypeName);
    }
    if(result.officialSealId !== ""){
        $('#officialSealId').val(result.officialSealId);
    }
}

function configAuditWin(result,form) {
    if(result === undefined || result === null){
        errorMsg("返回数据为空");
    }
    $('#templateName').val(result.templateName);
    $('#templateName2').text(result.templateName);
    $('#sealType').val(result.sealType);
    $('#sealTypeName').val(result.sealTypeName);
    $('#id').val(result.id);
    $('#tempRefId').val(result.refId);
    $('#templateNo').val(result.templateNo);
    $('#approvalId').val(result.approvalId);
    $('#remark').val(result.remark);
    $('#templateResource').val(result.resource);
    $('#templateResourceName').val(result.resourceName);
    if(result.sealType === 1){
        $("#officialSealId").parent().hide();
    }else {
        queryOfficalId(result.templateNo,form);
    }
}

/**
 * 编辑窗口
 * @param result
 */
function buildEditWin(form,layedit,index) {
    let id = GetUrlParam("id");
    let url = serverPre + "/manager/scs/v2/template/one/"+id;
    $.ajax({
        type: 'get',
        url: url,
        cache: false,
        headers: {"token": getCookie("token")},
        dataType: 'json',
        success: function (result) {
            if (result.code === 0) {
                var data = result.data.vo;
                //封装数据
                $('#channelId').val(data.channelId);
                $('#templateNo').val(data.templateNo);
                $('#templateName').val(data.templateName);
                $('#sealType').val(data.sealType);
                $('#version').val(data.version);
                $('#id').val(data.id);
                $('#remark').val(data.remark);
                $('#templateResource').val(data.resource);
                //封装radio模板来源
                buildRadioCheck(form,layedit,index,data);

                if(data.sealType === 1){
                    $("#officialSealId").parent().hide();
                }else {
                    let url = serverPre + "/manager/scs/v2/template/officialSealId/"+data.templateNo;
                    $.ajax({
                        url: url,
                        type: 'GET',
                        dataType: 'json',
                        async:false,
                        headers: {'token': getCookie('token')},
                        success: function (res) {
                            if (res.code === 0) {
                               let result =  res.data.list;
                                var ids = [];
                                $.each(result,function (i,item) {
                                    ids.push(item.code);
                                });
                                queryOfficalSeal(form,ids);
                            }
                        },
                        error: function (err) {
                            errorMsg(err);
                        }
                    });
                }
                form.render('select');
                form.render('checkbox');
            }
        }
    });
}

function buildRadioCheck(form,layedit,index,data) {
    $("input[name=templateResource][value=1]").attr("checked", data.resource == 1 ? true : false);
    $("input[name=templateResource][value=2]").attr("checked", data.resource == 2 ? true : false);
    form.render();
    //如果是线上编辑，则把模板内容赋值到textarea框中
    if(data.resource === 1){
        $("#templateEdit").parent().parent().hide();
        $("#templateExtId").parent().parent().show();
        form.render();
    }
    if(data.resource === 2){
        $("#templateExtId").parent().parent().hide();
        $("#templateEdit").parent().parent().show();
        var content = data.fileData;
        layedit.setContent(index, content, false);
        form.render();
    }
}

/**
 * 导出模板文件
 */
function exportTemplate(ids) {
    let url = serverPre + "/manager/scs/v2/template/export/";
    window.location.href=url+ids;
    return false;
}

/**
 * 文件上传
 */
function uploadFile(upload,uploadUrl) {
    upload.render({
        elem: '#uploadFile'
        ,url: uploadUrl,
        headers: {"token": getCookie("token")}
        ,accept: 'file' //普通文件
        ,exts:'ftl'
        ,done: function(res){
            if(res.code === 0){
                $('#templateExtId').val(res.data.templateExtId);
                $("#fileName").html(res.data.fileName)
                alert("上传成功！")
            }else {
                var msg = res.msg
                if (isBlank(msg)){
                    msg = "文件上传失败！"
                }
                layui.use('layer', function () {
                    var layer = layui.layer;
                    layer.msg(msg, {
                        icon: 5,
                        time: 2000,

                    });
                })
            }
        }
    });
}

/**
 * 提交表单
 * @param formData
 * @param url
 */
function submitForm(commitData,url) {
    layui.use(['form', 'layedit', 'laydate'], function(){
        var form = layui.form;
        //自定义验证规则
        form.verify({
            templateNameVerify: function(value){
                var len = getBLen(value);
                if(len > 50){
                    errorMsg("模板名称不能超过50字！")
                    return false;
                }
            },
            sealTypeVerify: function(value){
            },
            officialSealId:function(value){
            },
            remarksVerify:function(value){
                if(value == null){
                    return true;
                }
                var len = getBLen(value);
                if(len > 200){
                    errorMsg("模板备注不能超过200字！")
                    return false;
                }
            },
        });
        //监听提交
        form.on('submit(submitBtn)', function(data){
            saveTemplate(url,commitData);
            return false;
        });
    })



}
